package cn.liyicun.test.exception;

import cn.liyicun.test.dto.MyResultInfo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = HtmlException.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, HtmlException e) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        StringWriter sw=new StringWriter();
        PrintWriter pw=new PrintWriter(sw);
        e.printStackTrace(pw);
        mav.addObject("error_info", sw.toString());
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("error");
        log.error(e.getMessage(),e);
        return mav;
    }

       @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public MyResultInfo jsonErrorHandler2(HttpServletRequest req, Exception e) throws Exception {
        MyResultInfo  r = new MyResultInfo();
        r.setMessage(e.getMessage());
        r.setCode(MyResultInfo.SYS_ERROR);
        StringWriter sw=new StringWriter();
        PrintWriter pw=new PrintWriter(sw);
        e.printStackTrace(pw);
        r.setData( sw.toString());
        r.setUrl(req.getRequestURL().toString());log.error(e.getMessage(),e);
        return r;
    }
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public MyResultInfo jsonErrorHandler3(HttpServletRequest req, MyException e) throws Exception {
        MyResultInfo  r = new MyResultInfo();
        r.setMessage(e.getMessage());
        r.setCode(MyResultInfo.ERROR);
        StringWriter sw=new StringWriter();
        PrintWriter pw=new PrintWriter(sw);
        e.printStackTrace(pw);
        r.setData(sw.toString());
        r.setUrl(req.getRequestURL().toString());log.error(e.getMessage(),e);
        return r;
    }



}

